import { deepseek } from "~/utils/thirdpart-api";
import defineSessionEventHandler from '~/server/utils/session_verify';
import { to } from "await-to-js";
import { createChats, updateSessionById } from "../db/chat";

export default defineSessionEventHandler(async event => {
    const { msg } = await readBody(event);
    let { _id: session_id, title, content } = event.context.session;
    const time = +new Date();

    try {
        // get source
        const stream = await deepseek(msg);

        // create destination
        const eventStream = createEventStream(event, { autoclose: true });

        // terminated
        let closed = false;
        eventStream.onClosed(() => closed = true);

        // begin to resend
        new Promise<void>(async (resolve) => {
            const chunks = [];
            for await (const { content } of stream) {
                // record chunk
                chunks.push(content);
                // resend chunk
                if (!closed) await eventStream.push(JSON.stringify(content));
            }
            // send end flag
            await eventStream.push('[DONE]');

            // record messages
            await to(createChats(session_id, [
                { msg, time: +new Date(time) },
                { msg: chunks.join(''), time: +new Date() },
            ]));

            // update session
            if (!title || !content) {
                title = title || msg.slice(0, 20);
                content = content || chunks.join('').slice(0, 20);
                await to(updateSessionById(session_id, { title, content }));
            }

            // close stream
            resolve(await eventStream.close());
        });

        return eventStream.send();
    }
    catch (e) {
        console.dir(e);
    }
});